package com.alkalinesolutions.json.core.impl;

import java.io.IOException;

public class FormattedJSONTextEmitter extends CompactJSONTextEmitter {


	private int prettyPrintIndentation;
	private boolean usingTabsForIndenting;
	private boolean collapsingEmptyStructures;
	private boolean paddedWithTabs;
	private boolean firstEvent;
	private int indentationLevel;

	public FormattedJSONTextEmitter() {
		prettyPrintIndentation = 2;
		usingTabsForIndenting = false;
		collapsingEmptyStructures = true;
		paddedWithTabs = false;
		firstEvent = true;
		reset();
	}

	@Override
	public void reset() {
		super.reset();
		indentationLevel = 0;
	}

	public int getPrettyPrintIndentation() {
		return prettyPrintIndentation;
	}

	public void setPrettyPrintIndentation(final int prettyPrintIndentation) {
		this.prettyPrintIndentation = prettyPrintIndentation;
	}

	public boolean isUsingTabsForIndenting() {
		return usingTabsForIndenting;
	}

	public void setUsingTabsForIndenting(final boolean usingTabsForIndenting) {
		this.usingTabsForIndenting = usingTabsForIndenting;
	}

	public boolean isCollapsingEmptyStructures() {
		return collapsingEmptyStructures;
	}

	public void setCollapsingEmptyStructures(
			final boolean collapsingEmptyStructures) {
		this.collapsingEmptyStructures = collapsingEmptyStructures;
	}

	public boolean isPaddedWithTabs() {
		return paddedWithTabs;
	}

	public void setPaddedWithTabs(final boolean paddedWithTabs) {
		this.paddedWithTabs = paddedWithTabs;
	}

	private void indentLine() throws IOException {
		if (!firstEvent)
			writer.write('\n');
		final int count = prettyPrintIndentation * indentationLevel;
		for (int i = 0; i < count; i++)
			writer.write(usingTabsForIndenting ? '\t' : ' ');
	}

	@Override
	public void startStruct(final String key, boolean object) throws IOException {
		super.startStruct(key, object);
		indentationLevel++;
		firstEvent = false;
	}

	@Override
	public void endStruct(boolean object) throws IOException {
		indentationLevel--;
		if (collapsingEmptyStructures && first)
			writer.write(' ');
		else
			indentLine();
		super.endStruct(object);
	}

	@Override
	protected void emitNext() throws IOException {
		if (!first) {
			writer.write(',');
		}
		indentLine();
		first = false;
	}

	@Override
	protected void emitKey(final String k) throws IOException {
		if (k != null)
		{
			outputString(k);
			writer.write(paddedWithTabs ? "\t: " : " : "); //$NON-NLS-1$ //$NON-NLS-2$
		}
	}	
}